package book;

public class Libarary implements BookDao{
	//创建一个图书数组管理所有书
	private Book[] books;
	// 保存下标也是用来统计图书的实际本数
	private int index;
	
	// 无参构造，只管理10本书
	public Libarary() {
		books = new Book[10];
	}
	
	// 带参构造，size多少就管理多少
	public Libarary(int size) {
		books = new Book[size];
	}
	
	@Override
	public int insert(Book book) {
		if (index >= books.length) {
			return 0;
		} else {
			books[index] = book;
			index++;
			return 1;
		}
	}

	@Override
	public int update(Book book) {
		for(int i = 0 ; i < index; i ++) {
			if (books[i].getBookId() == book.getBookId()) {
				books[i] = book;
				return 1;
			}
		}
		return 0;
	}

	@Override
	public int delete(int bookId) {
		for (int i = 0 ; i < index; i++) {
			if (books[i].getBookId() == bookId) {
				// 循环删除
				for (int j = i; j < index-1; j++) {
					books[j] = books[j+1];
				}
				books[index-1] = null;
				index--;
				return 1;
			}
		}
		return 0;
	}

	@Override
	public Book selectById(int bookId) {
		for (int i = 0; i< index; i++) {
			if (books[i].getBookId() == bookId) {
				return books[i];
			}
		}
		return null;
	}

	@Override
	public Book[] selectAll() {
		Book[] copy = new Book[index];
		System.arraycopy(books, 0, copy, 0, index);
		return copy;
	}

	@Override
	public Book selectByName(String name) {
		for (int i = 0; i< index; i++) {
			// 字符串比较是否相等用equals
			if (books[i].getBookName().equals(name)) {
				return books[i];
			}
		}
		return null;
	}

}
